package com.jlcon.nas.biz.aria;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.googlecode.jsonrpc4j.ProxyUtil;
import com.jlcon.nas.biz.aria.dto.Aria2ActiveTask;
import com.jlcon.nas.config.NasConfig;

@Service
public class AriaClient {

	private final Aria2Service aria2Service;
	private NasConfig nasConfig;

	public AriaClient(NasConfig nasConfig) throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		JsonRpcHttpClient client = new JsonRpcHttpClient(objectMapper,new URL(nasConfig.getAria2Url()),new HashMap<String, String>());
		this.aria2Service = ProxyUtil.createClientProxy(getClass().getClassLoader(), Aria2Service.class, client);
		this.nasConfig = nasConfig;
	}
	
	public Object tellStatus(String gid) throws Throwable {
        return aria2Service.tellStatus("token:"+nasConfig.getAria2Token(),gid);
    }
	public Object getServers(String gid) throws Throwable {
		return aria2Service.getServers("token:"+nasConfig.getAria2Token(),gid);
	}
	public Object tellWaiting(Integer offset,Integer num) throws Throwable {
		return aria2Service.tellWaiting("token:"+nasConfig.getAria2Token(),offset,num);
	}
	public Object tellStopped(Integer offset,Integer num) throws Throwable {
		return aria2Service.tellStopped("token:"+nasConfig.getAria2Token(),offset,num);
	}
	
	public List<Aria2ActiveTask> tellActive(String...keys) throws Throwable {
		return aria2Service.tellActive("token:"+nasConfig.getAria2Token(),keys);
	}
	
	public Object getVersion() throws Throwable {
		return aria2Service.getVersion("token:"+nasConfig.getAria2Token());
	}
	
	public String addUri(String...uris) throws Throwable {
		return aria2Service.addUri("token:"+nasConfig.getAria2Token(),uris);
	}
	public void forceRemove(String[] gid) throws Throwable {
		if(gid == null || gid.length == 0) {
            throw new IllegalArgumentException("gid不能为空");
        }
		for(String id:gid) {
			aria2Service.forceRemove("token:"+nasConfig.getAria2Token(),id);
		}
	}
}
